<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input style="width: 240px" v-model="data.name" placeholder="请输入名称查询" prefix-icon="Search"></el-input>
      <el-button type="primary" @click="search">查 询</el-button>
      <el-button type="warning" @click="reset">重 置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="warning" @click="delBatch">批量删除</el-button>
      <!--<el-button type="info">导入</el-button>
      <el-button type="success">导出</el-button> -->
    </div>

    <!-- 原本的表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange"><!--返回选中行的数组-->
        <el-table-column type="selection" width="55" /><!--多选选择框-->
        <el-table-column label="账号" prop="username"/>
        <el-table-column label="头像">
          <template #default="scope">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" style="display: block; width: 40px;height: 40px;border-radius: 50%">
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="name"/>
        <el-table-column label="角色" prop="role"/>
        <el-table-column label="性别" prop="sex"/>
        <el-table-column label="工号" prop="no" />
        <el-table-column label="年龄" prop="age" />
        <el-table-column label="个人介绍" prop="descr" show-overflow-tooltip />
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="操作" width="120px">
        <template #default="scope"><!--范围是整个表格 -->
          <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle></el-button>
          <el-button @click="del(scope.row.id)" type="danger" :icon="Delete" circle></el-button>
        </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total,sizes, prev, pager, next,jumper"
            :total="data.total"
        /><!-- 重新加载一波 -->
      </div>
    </div>
    <!-- 弹出的新增修改表单,新增的表单名叫做formVisible -->
    <el-dialog title="员工信息"  v-model="data.formVisible" width="500" destroy-on-close><!-- 关闭时销毁上次输入 -->
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding-right:40px ;padding-top: 20px" >
        <el-form-item label="账号" prop="username"><!-- prop与下面规则里的username相对应-->
          <el-input :disabled="data.form.id" v-model="data.form.username" autocomplete="off" placeholder="请输入账号" style="padding-right: 200px"/>
        </el-form-item>
        <el-form-item label="部门">
          <el-select style="width: 100%" v-model="data.form.departmentId">
            <el-option v-for="item in data.departmentList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              action="http://localhost:8080/files/upload"
              type="picture"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称" style="padding-right: 200px"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="data.form.sex">
            <el-radio value="男" label="男"></el-radio>
            <el-radio value="女" label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号" prop="no">
          <el-input v-model="data.form.no" autocomplete="off" placeholder="请输入工号" style="padding-right: 200px"/>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number style="width: 170px" :min="18" v-model="data.form.age" autocomplete="off" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="个人介绍">
          <el-input type="textarea" :rows=3 v-model="data.form.descr" autocomplete="off" placeholder="请输入个人介绍" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup> //在script中定义引入
import {reactive ,ref} from"vue";//如果只是简单的单个数据需要响应式，优先使用 ref ；对于多个相关数据组成的对象或数组，用 reactive 会更简洁直观.它们都是用来维持数据与视图一致的
import {Edit, Search,Delete} from "@element-plus/icons-vue"
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref() //表单校验逻辑
const data =reactive({
  name:null ,
  tableData:[
  ],
  pageNum:1,
  pageSize:10,
  total:0,
  formVisible:false,
  form:{},
  ids:[],
  rules:{//定义表单输入规则，必填行
    username:[
      {required: true,message: '请输入账号', trigger:'blur'}//当用户离开当前输入字段（失去焦点）时，立即触发该字段的验证逻辑，避免用户填写完所有字段后才发现错误。
    ],
    name:[
      {required: true,message: '请输入名称', trigger:'blur'}//当用户离开当前输入字段（失去焦点）时，立即触发该字段的验证逻辑，避免用户填写完所有字段后才发现错误。
    ],
    no:[
      {required: true,message: '请输入工号', trigger:'blur'}//当用户离开当前输入字段（失去焦点）时，立即触发该字段的验证逻辑，避免用户填写完所有字段后才发现错误。
    ]
  },
  departmentList:[]

})

request.get('/department/selectAll').then(res =>{
  data.departmentList = res.data
})
const search =() =>{
  if(data.name === null){
    ElMessage.warning('请选择数据')
    return
  }
  load()
}
const load =() =>{ //定义重置方法load,并且重置之后的是分页之后的表格
  request.get('/employee/selectPage',{ //?pageNum=1&pageSize=10,含有俩个参数
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }) .then(res => {
    data.tableData = res.data.list
    data.total = res.data.total
  })
}
load() //之后立马重置一下，表中才会有数据

const reset = () =>{
  data.name = null
  load()
}//重置参数清空再重新加载
const handleAdd = () =>{
  data.formVisible = true
  data.form ={}
}

const save = () =>{ //在一个保存里做俩种操作，一个是新增，一个是更新
  formRef.value.validate((valid) => {
    if (valid) {
      data.form.id? update(): add()  //三目表达式，（）有值是update，没有值是add
    }
  })
}

const add =() =>{
  request.post('/employee/add',data.form).then(res =>{    //新增的对象无id，编辑对象里包含id
    if(res.code==='200'){
      data.formVisible=false
      ElMessage.success('操作成功')
      load() //新增后一定要重新加载最新数据
    } else{
      ElMessage.error(res.msg)
    }
  })
}

const update =() =>{
  request.put('/employee/updateById',data.form).then(res =>{
    if(res.code==='200'){
      data.formVisible=false
      ElMessage.success('操作成功')
      load() //新增后一定要重新加载最新数据
    } else{
      ElMessage.error(res.msg)
    }
  })
}

const handleUpdate =(row) =>{
  data.form = JSON.parse(JSON.stringify(row))//复制一个新对象用于编辑，这样就不会影响行对象的数据
  data.formVisible = true
}//带数据过来的，一行数据

const del = (id) =>{
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗','删除确认',{type:'warning'}).then(()=>{ //二次确认
    request.delete('/employee/deleteById/' +id).then(res =>{
      if(res.code==='200'){
        data.formVisible=false
        ElMessage.success('操作成功')
        load() //删除后一定要重新加载最新数据
      } else{
        ElMessage.error(res.msg)
      }
    })
  }).catch() //不确认到catch里去了
}

const handleSelectionChange = (rows) =>{  //返回所有选中的行对象数组
  //从选中的行数组里面取出所有行的id组成一个新的数组
  data.ids = rows.map(row => row.id)//map是遍历回调函数
  console.log(data.ids)
}

const delBatch = () => {
  if(data.ids.length === 0){
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗','删除确认',{type:'warning'}).then(() => {
    request.delete('/employee/deleteBatch',{data: data.ids}).then(res => {
      if(res.code==='200'){
        ElMessage.success('操作成功')
        load() //删除后一定要重新加载最新数据
      } else{
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}

const handleAvatarSuccess = (res) => {
  console.log(res.data)
  data.form.avatar = res.data //avatar是头像属性，需要在后台加入
}



</script>
<style scoped>

</style>